<template>
    <div>
        <a-table :columns="columns" :data-source="indexData" :pagination="false" row-key="_rowKey">
            <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'name'">
                    <a-input v-model:value="record.name" placeholder="索引名称" />
                </template>
                <template v-if="column.dataIndex === 'type'">
                    <a-select v-model:value="record.type" style="width: 100%">
                        <a-select-option value="PRIMARY">主键</a-select-option>
                        <a-select-option value="UNIQUE">唯一索引</a-select-option>
                        <a-select-option value="INDEX">普通索引</a-select-option>
                    </a-select>
                </template>
                <template v-if="column.dataIndex === 'columns'">
                    <a-select
                        v-model:value="record.columns"
                        mode="multiple"
                        style="width: 100%"
                        placeholder="选择字段"
                    >
                        <a-select-option v-for="field in fields" :key="field.column_name" :value="field.column_name">
                            {{ field.column_name }}
                        </a-select-option>
                    </a-select>
                </template>
                <template v-if="column.dataIndex === 'actions'">
                    <a-space>
                        <a-button type="link" danger @click="handleDelete(record)">删除</a-button>
                    </a-space>
                </template>
            </template>
        </a-table>



        <!-- 新增索引弹窗 -->
        <a-modal
            v-model:visible="showAddModal"
            title="新增索引"
            @ok="handleAdd"
            @cancel="showAddModal = false"
        >
            <a-form :model="newIndex" layout="vertical">
                <a-form-item label="索引名称" required>
                    <a-input v-model:value="newIndex.name" placeholder="请输入索引名称" />
                </a-form-item>
                <a-form-item label="索引类型" required>
                    <a-select v-model:value="newIndex.type">
                        <a-select-option value="PRIMARY">主键</a-select-option>
                        <a-select-option value="UNIQUE">唯一索引</a-select-option>
                        <a-select-option value="INDEX">普通索引</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="索引字段" required>
                    <a-select
                        v-model:value="newIndex.columns"
                        mode="multiple"
                        placeholder="请选择字段"
                    >
                        <a-select-option v-for="field in fields" :key="field.column_name" :value="field.column_name">
                            {{ field.column_name }}
                        </a-select-option>
                    </a-select>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'

const props = defineProps<{
    table_name: string
    fields: any[]
}>()

const emits = defineEmits(['update:indexes', 'update:sql', 'change:table_name'])

const columns = [
    {
        title: '索引名称',
        dataIndex: 'name',
        width: 200,
    },
    {
        title: '索引类型',
        dataIndex: 'type',
        width: 150,
    },
    {
        title: '索引字段',
        dataIndex: 'columns',
    },
    {
        title: '操作',
        dataIndex: 'actions',
        width: 120,
        align: 'center',
    }
]

const indexData = ref<any[]>([])
const showAddModal = ref(false)

const newIndex = reactive({
    name: '',
    type: 'INDEX',
    columns: [] as string[]
})

// 监听字段变化，更新索引列表
watch(
    () => props.fields,
    (newFields) => {
        const indexes: any[] = []
        
        // 处理主键
        const primaryKey = newFields.find(f => f.column_key === 'PRI')
        if (primaryKey) {
            indexes.push({
                _rowKey: 'primary',
                name: 'PRIMARY',
                type: 'PRIMARY',
                columns: [primaryKey.column_name]
            })
        }

        // 处理唯一索引
        const uniqueFields = newFields.filter(f => f.column_key === 'UNI')
        uniqueFields.forEach(field => {
            indexes.push({
                _rowKey: `unique_${field.column_name}`,
                name: field.column_name,
                type: 'UNIQUE',
                columns: [field.column_name]
            })
        })

        // 处理普通索引
        const indexFields = newFields.filter(f => f.column_key === 'MUL')
        indexFields.forEach(field => {
            indexes.push({
                _rowKey: `index_${field.column_name}`,
                name: `idx_${field.column_name}`,
                type: 'INDEX',
                columns: [field.column_name]
            })
        })

        indexData.value = indexes
        emits('update:indexes', indexes)
        emits('update:sql')
        console.log(123123)
    },
    { immediate: true, deep: true }
)

// 处理删除索引
function handleDelete(record: any) {
    const index = indexData.value.findIndex(item => item._rowKey === record._rowKey)
    if (index > -1) {
        // 找到对应的字段并更新其键状态
        record.columns.forEach((columnName: string) => {
            const field = props.fields.find(f => f.column_name === columnName)
            if (field) {
                // 根据索引类型更新字段的键状态
                if (record.type === 'PRIMARY' && field.column_key === 'PRI') {
                    field.column_key = ''
                } else if (record.type === 'UNIQUE' && field.column_key === 'UNI') {
                    field.column_key = ''
                } else if (record.type === 'INDEX' && field.column_key === 'MUL') {
                    field.column_key = ''
                }
            }
        })

        // 删除索引
        indexData.value.splice(index, 1)
        emits('update:indexes', indexData.value)
        emits('update:sql')
    }
}

// 处理添加索引
function handleAdd() {
    if (!newIndex.name || !newIndex.type || !newIndex.columns.length) {
        return
    }

    const index = {
        _rowKey: `${newIndex.type.toLowerCase()}_${newIndex.name}`,
        name: newIndex.name,
        type: newIndex.type,
        columns: newIndex.columns
    }

    indexData.value.push(index)
    emits('update:indexes', indexData.value)
    emits('update:sql')
    
    // 重置表单
    newIndex.name = ''
    newIndex.type = 'INDEX'
    newIndex.columns = []
    showAddModal.value = false
}

// 获取字段标签颜色
function getFieldTagColor(field: any) {
    if (field.column_key === 'PRI') return 'blue'
    if (field.column_key === 'UNI') return 'purple'
    if (field.column_key === 'MUL') return 'green'
    return 'default'
}

// // 处理字段点击
// function handleFieldClick(field: any) {
//     // 如果字段已经是主键，则不允许添加到其他索引
//     if (field.column_key === 'PRI') {
//         return
//     }

//     // 如果字段已经是唯一索引，则只能添加到普通索引
//     if (field.column_key === 'UNI') {
//         const index = {
//             _rowKey: `index_${field.column_name}`,
//             name: `idx_${field.column_name}`,
//             type: 'INDEX',
//             columns: [field.column_name]
//         }
//         indexData.value.push(index)
//         emits('update:indexes', indexData.value)
//         return
//     }

//     // 如果字段已经是普通索引，则只能添加到唯一索引
//     if (field.column_key === 'MUL') {
//         const index = {
//             _rowKey: `unique_${field.column_name}`,
//             name: field.column_name,
//             type: 'UNIQUE',
//             columns: [field.column_name]
//         }
//         indexData.value.push(index)
//         emits('update:indexes', indexData.value)
//         return
//     }

//     // 如果字段没有任何索引，则添加到普通索引
//     const index = {
//         _rowKey: `index_${field.column_name}`,
//         name: `idx_${field.column_name}`,
//         type: 'INDEX',
//         columns: [field.column_name]
//     }
//     indexData.value.push(index)
//     emits('update:indexes', indexData.value)
// }

// 暴露方法
defineExpose({
    getIndexes: () => indexData.value,
    refresh: () => {
        // 触发字段监听器
        const fields = [...props.fields]
        props.fields.splice(0, props.fields.length, ...fields)
    }
})
</script>

